﻿@using PMS.Web.Models.Customers
@using PMS.Web.FrontUI
@model BindAccountModel
@{
    Layout = "_AdminHomeLayout";
}

@section CssStyles{
    <style type="text/css">
        .formitem-box {
            width: 380px;
            padding: 20px;
            margin: 0 auto;
            background-color: #ffffff;
        }

        .formitem-box .layui-form-item {
            position: relative;
        }

        .formitem-box .layui-form-item .layui-input {
            padding-left: 38px;
        }

        .input-prefix-icon {
            position: absolute;
            left: 1px;
            top: 1px;
            width: 38px;
            line-height: 36px;
            text-align: center;
            color: #d2d2d2;
        }

        .codeImage {
            cursor: pointer;
            height: 38px;
            width: 130px;
        }
    </style>
}

<div class="formitem-box layui-form" lay-filter="bindAccountForm">
    @if (Model.BindMode == AccountBindMode.Email)
    {
        if (!string.IsNullOrEmpty(Model.Email))
        {
            <div class="layui-form-item">
                <label class="input-prefix-icon layui-icon layui-icon-email" for="originEmail"></label>
                <input type="text" id="originEmail" value="@Html.HideEmail(Model.Email)" readonly class="layui-input" />
            </div>
        }
        <div class="layui-form-item">
            <label class="input-prefix-icon layui-icon layui-icon-email" for="userEmail"></label>
            <input type="text" name="@Model.NameOf(m => m.Email)" id="userEmail" placeholder="@Model.DisplayName(m => m.Email)" lay-verify="required|email" autocomplete="off" class="layui-input" />
        </div>
        <div class="layui-form-item">
            <div class="layui-row">
                <div class="layui-col-xs7">
                    <label class="input-prefix-icon layui-icon layui-icon-vercode" for="emailCode"></label>
                    <input type="text" name="@Model.NameOf(m => m.EmailCode)" id="emailCode" lay-verify="required" placeholder="新绑定邮箱验证码" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-col-xs5">
                    <div style="margin-left: 10px;">
                        <button type="button" class="layui-btn layui-btn-primary layui-btn-fluid" id="getEmailCode">获取验证码</button>
                    </div>
                </div>
            </div>
        </div>
    }
    else if (Model.BindMode == AccountBindMode.MobilePhone)
    {
        if (!string.IsNullOrEmpty(Model.Mobile))
        {
            <div class="layui-form-item">
                <label class="input-prefix-icon layui-icon layui-icon-cellphone" for="originMobile"></label>
                <input type="text" id="originMobile" value="@Html.HideMobile(Model.Mobile)" readonly class="layui-input">
            </div>
        }
        <div class="layui-form-item">
            <label class="input-prefix-icon layui-icon layui-icon-cellphone" for="userMobile"></label>
            <input type="text" name="@Model.NameOf(m => m.Mobile)" id="userMobile" placeholder="@Model.DisplayName(m => m.Mobile)" lay-verify="required|phone|number" autocomplete="off" class="layui-input">
        </div>
        <div class="layui-form-item">
            <div class="layui-row">
                <div class="layui-col-xs7">
                    <label class="input-prefix-icon layui-icon layui-icon-vercode" for="smsCode"></label>
                    <input type="text" name="@Model.NameOf(m => m.SMSCode)" id="smsCode" lay-verify="required" placeholder="新绑定手机号验证码" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-col-xs5">
                    <div style="margin-left: 10px;">
                        <button type="button" class="layui-btn layui-btn-primary layui-btn-fluid" id="getSmsCode">获取验证码</button>
                    </div>
                </div>
            </div>
        </div>
    }
    else if (Model.BindMode == AccountBindMode.LoginName)
    {
        if (!string.IsNullOrEmpty(Model.LoginName))
        {
            <div class="layui-form-item">
                <label class="input-prefix-icon layui-icon layui-icon-username" for="originLoginname"></label>
                <input type="text" id="originLoginname" value="@Model.LoginName" readonly class="layui-input">
            </div>
        }
        <div class="layui-form-item">
            <label class="input-prefix-icon layui-icon layui-icon-username" for="userLoginname"></label>
            <input type="text" name="@Model.NameOf(m => m.LoginName)" id="userLoginname" placeholder="@Model.DisplayName(m => m.LoginName)" lay-verify="required" autocomplete="off" class="layui-input">
            <input type="text" id="userMobile" value="@Model.Mobile" class="layui-hide" />
        </div>
        <div class="layui-form-item">
            <div class="layui-row">
                <div class="layui-col-xs7">
                    <label class="input-prefix-icon layui-icon layui-icon-vercode" for="smsCode"></label>
                    <input type="text" name="@Model.NameOf(m => m.SMSCode)" id="smsCode" lay-verify="required" placeholder="@Model.DisplayName(m => m.SMSCode)" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-col-xs5">
                    <div style="margin-left: 10px;">
                        <button type="button" class="layui-btn layui-btn-primary layui-btn-fluid" id="getSmsCode">获取验证码</button>
                    </div>
                </div>
            </div>
        </div>
    }
    @if (Model.DisplayCaptcha)
    {
        <div class="layui-form-item">
            <div class="layui-row imgCaptcha">
                <div class="layui-col-xs7">
                    <label class="input-prefix-icon layui-icon layui-icon-auz" for="captchaAnswer"></label>
                    <input type="text" name="@Model.NameOf(m => m.CaptchaAnswer)" id="captchaAnswer" lay-verify="required" placeholder="@Model.DisplayName(m => m.CaptchaAnswer)" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-col-xs5">
                    <div style="margin-left: 10px;" class="">
                        <input type="text" name="@Model.NameOf(m => m.EncryptCaptcha)" value="" class="layui-hide" />
                        <img src="/lib/PearAdminLayui/admin/images/captcha.gif" class="codeImage" />
                    </div>
                </div>
            </div>
        </div>
    }

    <input type="text" class="layui-hide" name="@Model.NameOf(m => m.Id)" value="@Model.Id.ToString()" />
    <input type="text" class="layui-hide" name="@Model.NameOf(m => m.DisplayCaptcha)" value="@Model.DisplayCaptcha.ToString()" />
    <input type="text" class="layui-hide" name="@Model.NameOf(m => m.BindMode)" value="@Model.BindMode.ToString()" />
    <div class="layui-form-item">
        <button type="button" id="accountBindSubmitBtn" class="layui-btn layui-btn-normal layui-btn-sm" lay-submit="" lay-filter="accountBindSubmit">
            <i class="layui-icon layui-icon-ok"></i>
            提交
        </button>
    </div>
</div>

@await Component.InvokeAsync("ModelValidateError")

@section Scripts{
    <script type="text/javascript">
        layui.use(['jquery', 'form', 'element', 'http', 'loading', 'popup', 'laytpl', 'button'], function () {
            var $ = layui.jquery,
                form = layui.form,
                element = layui.element,
                http = layui.http,
                loading = layui.loading,
                popup = layui.popup,
                laytpl = layui.laytpl,
                button = layui.button;

            var imageVerified = false;
            var rejectWhenLoading = false;
            var initPageComponent = function () {
                var captchaModule = $(".imgCaptcha");
                getCaptchData(130, 38);

                if ($("img.codeImage").length > 0) {
                    $("img.codeImage").on("click", function () {
                        getCaptchData(130, 38);
                    });
                } else {
                    imageVerified = true;
                }

                $("#getSmsCode").on("click", function () {
                    if (rejectWhenLoading)
                        return false;
                    $(".layui-input").removeAttr("failure");
                    var $userMobile = $("#userMobile");
                    if ($userMobile.length > 0) {
                        if (!PMSUtils.isValidMobile($userMobile.val())) {
                            popup.failure("请输入正确的手机号码");
                            $userMobile.focus();
                            return false;
                        }
                    }
                    var $captchaAnswer = $("#captchaAnswer");
                    if ($captchaAnswer.length > 0) {
                        if ($captchaAnswer.val().trim().length <= 0) {
                            popup.failure("请输入图形验证码");
                            $captchaAnswer.focus();
                            return false;
                        }
                    }
                    sendVerifyCode($(this).attr('id'), backendwebapiConfig.sendchangaccountverifycodeSMS);
                });

                $("#getEmailCode").on("click", function () {
                    if (rejectWhenLoading)
                        return false;
                    $(".layui-input").removeAttr("failure");
                    var $userEmail = $("#userEmail");
                    if ($userEmail.length > 0) {
                        if (!PMSUtils.isValidEmail($userEmail.val())) {
                            popup.failure("请输入正确的邮箱地址");
                            $userEmail.focus();
                            return false;
                        }
                    }
                    var $captchaAnswer = $("#captchaAnswer");
                    if ($captchaAnswer.length > 0) {
                        if ($captchaAnswer.val().trim().length <= 0) {
                            popup.failure("请输入图形验证码");
                            $captchaAnswer.focus();
                            return false;
                        }
                    }
                    sendVerifyCode($(this).attr('id'), backendwebapiConfig.sendchangaccountverifycodeEmail);
                });

                form.on('submit(accountBindSubmit)', function (data) {
                    if (!imageVerified) {
                        popup.failure("图形验证码过期或校验错误,请重新验证");
                        return false;
                    }
                    layer.confirm('账号将重绑定，同时与本账号绑定的第三方登录认证信息将被清空，用户需要重新绑定，是否继续?', { icon: 3, title: '提示信息' }, function (index) {
                        //do something
                        http.post(backendwebapiConfig.customerchangaccount, data.field, null)
                            .done(function (response) {
                                if (response.state && response.state === 200) {
                                    popup.success(response.message, function () {
                                        PMSUtils.closePopupWindow();
                                    });
                                }
                            }).fail(function (error) {
                                //For ModelValidation
                                if (error.status && error.status === 400) {
                                    var validator = error.responseJSON;
                                    if (validator.ErrorCode && validator.ErrorCode === "FluentValidationError") {
                                        var validateTpl = document.getElementById('validateResultTpl').innerHTML;
                                        laytpl(validateTpl).render(validator, function (html) {
                                            http.ajax.showError({
                                                message: '提示信息',
                                                details: html
                                            });
                                        });

                                        //标红校验错误的数据框
                                        layui.each(validator.Errors, function (index, item) {
                                            var inputField = item.ErrorField;
                                            $("input[name=" + inputField + "]").attr('failure', '');
                                        });
                                    }
                                }
                            });
                        layer.close(index);
                    });

                    return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                });

                function sendVerifyCode(buttonId, apiUrl) {
                    var formData = form.val("bindAccountForm");
                    http.post(apiUrl, formData, null)
                        .done(function (response) {
                            if (response.state && response.state === 200) {
                                popup.success(response.message, function () {
                                    imageVerified = true;
                                    rejectWhenLoading = true;
                                    button.load({
                                        elem: "#" + buttonId,
                                        time: 60000,
                                        done: function () {
                                            //imageVerified = false;
                                            rejectWhenLoading = false;
                                        }
                                    });
                                });
                            }
                        }).fail(function (error) {
                            //For ModelValidation
                            if (error.status && error.status === 400) {
                                var validator = error.responseJSON;
                                if (validator.ErrorCode && validator.ErrorCode === "FluentValidationError") {
                                    var validateTpl = document.getElementById('validateResultTpl').innerHTML;
                                    laytpl(validateTpl).render(validator, function (html) {
                                        http.ajax.showError({
                                            message: '提示信息',
                                            details: html
                                        });
                                    });

                                    //标红校验错误的数据框
                                    layui.each(validator.Errors, function (index, item) {
                                        var inputField = item.ErrorField;
                                        $("input[name=" + inputField + "]").attr('failure', '');
                                    });
                                }
                            }
                        });
                }

                function getCaptchData(imgw, imgh) {
                    if (captchaModule.length > 0) {
                        http.get(backendwebapiConfig.getcaptcha,
                            { imgwidth: imgw, imgheight: imgh },
                            function () { //beforeSend
                                loading.block({ type: 5, elem: '.imgCaptcha', msg: '' })
                            }
                        ).done(function (response) {
                            if (response.state && response.state === 200) {
                                $("#captchaAnswer").val("");
                                $("input[name=EncryptCaptcha]").val(response.data.Answer);
                                $(".codeImage").attr('src', response.data.CaptchBase64Data);
                            }
                        }).fail(function (error) {
                            http.ajax.logError(error);
                        }).always(function () {
                            loading.blockRemove(".imgCaptcha", 100);
                        });
                    }
                }
            };

            initPageComponent();
        });
    </script>
}
